<template>
  <section>
    <el-row type="flex" class="title" align="middle">
      <el-col :span="8" class="title-left">
        <span>
          <span
            class="circle circle-online"
            v-if="data.is_online == true"
          ></span>
          <span
            class="circle circle-offline"
            v-if="data.is_online == false"
          ></span>
          <span
            class="circle circle-undefind"
            v-if="data.is_online == 'undefind'"
          ></span>
          <span class="enabled-color">{{ data.live_name }}</span>
        </span>
      </el-col>
      <el-col :span="16" class="title-right">
        <div class="button-group">
          <el-tooltip placement="top" content="告警">
            <el-button
              type="primary"
              circle
              icon="iconfont icon-jinggao"
              :class="alarmClass"
              @click="alarm"
              plain
            ></el-button>
          </el-tooltip>
          <el-tooltip placement="top" content="录像">
            <span>
              <el-button
                type="primary"
                circle
                icon="iconfont icon-shipinluxiang"
                @click="recordVideo"
                plain
                :loading="recordVideoVisible"
                :disabled="!connected"
              ></el-button>
            </span>
          </el-tooltip>
          <el-tooltip placement="top" content="回放">
            <el-button
              type="primary"
              circle
              icon="iconfont icon-huifang"
              @click="playback"
              plain
            ></el-button>
          </el-tooltip>
          <el-tooltip placement="top" content="截图">
            <span>
              <el-button
                type="primary"
                circle
                icon="iconfont icon-jietu"
                @click="screenshot"
                plain
                :loading="screenshotVisible"
                :disabled="!connected"
              ></el-button>
            </span>
          </el-tooltip>
          <el-tooltip placement="top" content="图片">
            <el-button
              type="primary"
              circle
              icon="iconfont icon-yulan"
              @click="viewScreenshot"
              plain
              v-if="audioShow"
            ></el-button>
          </el-tooltip>
          <el-tooltip placement="top" content="语音对讲">
            <audio-button
              :data="data"
              :disabled="audioDisable"
              v-if="audioShow"
            ></audio-button>
          </el-tooltip>
          <el-tooltip placement="top" content="录音">
            <span>
              <el-button
                type="primary"
                circle
                icon="iconfont icon-luyin"
                @click="recordAudio"
                plain
                :disabled="audioDisable"
              ></el-button>
            </span>
          </el-tooltip>
          <!-- <el-tooltip placement="top" content="设置">
            <el-button
              type="primary"
              circle
              icon="iconfont icon-shezhi"
              @click="setting"
              plain
            ></el-button>
          </el-tooltip> -->
        </div>
      </el-col>
    </el-row>
    <div class="video-container">
      <!-- <video ref="video" style="width:100%; height: 100%" controls autoplay></video> -->

      <video-player
        :class="videoClass"
        ref="videoPlayer"
        :options="options"
        :playsinline="true"
        customEventName="customstatechangedeventname"
        @pause="onPlayerPause($event)"
        @ended="onPlayerEnded($event)"
        @waiting="onPlayerWaiting($event)"
        @playing="onPlayerPlaying($event)"
        @loadeddata="onPlayerLoadeddata($event)"
        @timeupdate="onPlayerTimeupdate($event)"
        @canplay="onPlayerCanplay($event)"
        @canplaythrough="onPlayerCanplaythrough($event)"
        @statechanged="playerStateChanged($event)"
        @play="onPlayerPlay($event)"
        @ready="playerReadied"
      ></video-player>
    </div>
    <video-playback
      v-if="playbackVisible"
      :data="data"
      @close="closeDetails"
    ></video-playback>
    <video-screenshot
      v-if="viewScreenshotVisible"
      :data="data"
      @close="closeDetails"
    ></video-screenshot>
    <record-audio
      v-if="recordAudioVisible"
      :data="data"
      @close="closeDetails"
    ></record-audio>

    <!-- <video-setting
      :visible.sync="settingVisible"
      :objectTag="objectTag"
      @change="settingChange"
    ></video-setting> -->
  </section>
</template>
<script>
	
	/* eslint-disable */
import "video.js/dist/video-js.css";
import { videoPlayer } from "vue-video-player";
// import "videojs-flash";
import "./iconfont/iconfont.css";
import VideoPlayback from "./playback";
import VideoScreenshot from "./screenshot";
import AudioButton from "./record-audio/audio-button";
import RecordAudio from "./record-audio/record";
// import VideoSetting from "./setting/index";
import { recordVideo, screenshot } from "./api";
import webrtc from "./webRTC";
import flv from "./flv";

import { mapGetters } from "vuex";

export default {
  name: "FtVideoPlayer",
  mixins: [flv, webrtc],
  components: {
    videoPlayer,
    VideoPlayback,
    VideoScreenshot,
    // VideoSetting,
    AudioButton,
    RecordAudio,
  },
  props: {
    objectTag: String, //是否根据ojbectTag查出摄像头信息（objectTag来自模型tag, 如果没有objectTag需要在实例上传进来一个固定的uuid）
    autoplay: Boolean, //是否自动播放
    poster: String, //预览图地址
    videoClass: {
      type: String,
      default: "video-player vjs-custom-skin",
    },
    source: {
      //播放类型和播放地址
      type: Object,
      default: () => {
        return {
          type: "application/webrtc",
          src: "webrtc://192.168.1.216/live/testwebrtc",
        };
      },
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    showOperationPanel: Boolean, //是否显示操作版
  },

  data() {
    // let swf = require('./video-js.swf');
    return {
      //rtmp://117.39.30.132:1935/live/camera_3_55
      options: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: this.autoplay, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        // techOrder: ["html5","flash"], //设置顺序
        techOrder: ["html5"], //设置顺序
        // flash: {
        //   hls: { withCredentials: false },
        //   swf: swf.default? swf.default: swf
        // },
        // sources:[{
        //     type: 'application/webrtc',
        //     src: 'webrtc://192.168.1.216/live/testwebrtc'
        // }],
        html5: { hls: { withCredentials: false } },
        poster: this.poster, //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, //全屏按钮
        },
      },
      recordVideoVisible: false,
      screenshotVisible: false,
      recordAudioVisible: false,
      playbackVisible: false,
      viewScreenshotVisible: false,
      audioClicked: false,
      settingVisible: false,
      screenshotTime: [],
      operationBtn: {},
      alarmClass: "alarm-unactived",
      connected: false,
      playerBigBtn: null,
      audioDisable: false,
      audioShow: true,
    };
  },
  computed: {
    ...mapGetters(["playerType", "service"]),
  },
  watch: {
    showOperationPanel: {
      immediate: true,
      handler: function (v) {
        this.$nextTick(() => {
          if (v) {
            this.operationBtn.style.display = "block";
          } else {
            this.operationBtn.style.display = "none";
          }
        });
      },
    },
    // source:{//rtmp播放方案
    //   immediate: true,
    //   handler: function(source){
    //     if(!!this.source.src){

    //       if(this.playerType === 'rtmp'){
    //         this.$set(this.options, 'sources', [{//播放示例
    //           type: this.source.type,
    //           src: this.source.src
    //         }])
    //       }

    //     }
    //   }
    // },
    data: {
      immediate: true,
      deep: true,
      handler: function (data) {
        if (data.is_alarm) this.alarmClass = "alarm-actived";
        else this.alarmClass = "alarm-unactived";
        if (data.push_dev_type == 2) this.audioShow = false;
        //rtmp摄像头
        else this.audioShow = true;
        if (data.is_online != true && this.playerBigBtn != null) {
          this.playerBigBtn.style.display = "block";
        }
      },
    },
    playerType: {
      immediate: true,
      handler: function (type) {
        this.$nextTick(() => {
          this.initPlayer();
        });
      },
    },
  },
  mounted: function () {
    this.operationBtn = this.createOperationBtn();
    window.addEventListener("beforeunload", (e) => {
      this.disposeVideo();
    });
    if (window.location.protocol == "http:") this.audioDisable = true;
    if (this.data.push_dev_type == 2) this.audioDisable = true; //rtmp摄像头
  },
  methods: {
    initPlayer() {

      this.playerBigBtn = this.$refs.videoPlayer.$el.querySelector(
        ".vjs-big-play-button"
      );
      this.playerBigBtn.onclick = (e) => {
      
        if (this.data.is_online === false) {
          this.$message({
            type: "warning",
            message: "该设备不在线",
          });
          return;
        }
        if (this.data.is_disable == 1) {
          this.$message({
            type: "warning",
            message: "该设备被禁止推流",
          });
          return;
        }
        this.playerBigBtn.style.display = "none";
        let video = this.data;
        this.$emit("play", this.source);

        let dom = this.$refs.videoPlayer.$el.querySelector(".vjs-tech");
        let url = null;

        let s = this.service.filter((item) => {
          let host_ip = video.push_domain_name.split(":")[0];
          return host_ip == item.host_ip;
        });
        s = s[0];
        let port = null;

        if (this.playerType == "webrtc") {
          port = s.srs_http_api_port;
          url =
            "webrtc://" +
            video.push_domain_name.split(":")[0] +
            ":" +
            port +
            "/" +
            video.push_app_name +
            "/" +
            video.push_stream_name +
            (video.authed_key ? `?authedkey=${video.authed_key}` : "");
          this.webrtcStartVideo(dom, url);
        } else if (this.playerType == "flv") {
          port = s.srs_http_server_port;
          url =
            "http://" +
            video.push_domain_name.split(":")[0] +
            ":" +
            port +
            "/" +
            video.push_app_name +
            "/" +
            video.push_stream_name +
            ".flv" +
            (video.authed_key ? `?authedkey=${video.authed_key}` : "");
            //gb28181转flv后音频格式错误导致flv无法播放 暂时禁用解析音频
          this.flvStartVideo(dom, url);
        }
      };
    },

    createOperationBtn() {
      let videoCtrBar = this.$refs.videoPlayer.$el.querySelector(
        ".vjs-control-bar"
      );
      if (videoCtrBar.querySelector(".vjs-operation")) return;

      let optContainer = document.createElement("div");
      optContainer.className = "vjs-operation";

      function createElement({ left, right, top, bottom, rotate }) {
        let div = document.createElement("button");
        div.innerText = "<";
        div.className = "vjs-operation-btn";
        div.style.right = right;
        div.style.left = left;
        div.style.top = top;
        div.style.bottom = bottom;
        div.style.transform = rotate;
        optContainer.appendChild(div);
        return div;
      }
      let topBtn = createElement({
        left: "calc(50% - 15px)",
        top: 0,
        rotate: "rotate(90deg)",
      });
      let bottomBtn = createElement({
        left: "calc(50% - 15px)",
        bottom: 0,
        rotate: "rotate(270deg)",
      });
      let leftBtn = createElement({ left: 0, top: "calc(50% - 15px)" });
      let rightBtn = createElement({
        right: 0,
        top: "calc(50% - 15px)",
        rotate: "rotate(180deg)",
      });
      videoCtrBar.appendChild(optContainer);

      topBtn.onclick = () => this.$emit("directive", 0);
      bottomBtn.onclick = () => this.$emit("directive", 1);
      leftBtn.onclick = () => this.$emit("directive", 2);
      rightBtn.onclick = () => this.$emit("directive", 3);

      let narrowBtn = createElement({ right: "100px", bottom: "60px" });
      narrowBtn.innerText = "-";
      let enlarge = createElement({ right: "100px", bottom: "10px" });
      enlarge.innerText = "+";

      narrowBtn.onclick = () => this.$emit("directive", 5);
      enlarge.onclick = () => this.$emit("directive", 4);
      return optContainer;
    },
    onPlayerPlay(event) {
      console.log("play");
      // this.$emit('play', event)
    },
    onPlayerPause(event) {
      this.connected = false;
      this.audioDisable = true;
      this.$refs.videoPlayer.player.pause();
      this.$emit("stop", event); //
      this.$emit("pause", event);
      this.playerBigBtn.style.display = "block";
      // this.disposeVideo();
    },
    onPlayerEnded(event) {
      this.$emit("ended", event);
    },
    onPlayerWaiting(event) {
      // this.createStopBtn();
      console.log("waiting");
      this.$emit("waiting", event);
    },
    onPlayerPlaying(event) {
      this.$emit("playing", event);
    },
    onPlayerLoadeddata(event) {
      this.$emit("loadeddata", event);
    },
    onPlayerTimeupdate(event) {
      this.$emit("timeupdate", event);
    },
    onPlayerCanplay(event) {
      console.log("onPlayerCanplay");
      this.$emit("canplay", event);
      // this.connecting = false;
      this.connected = true;
      this.audioDisable = false;
    },
    onPlayerCanplaythrough(event) {
      this.$emit("canplaythrough", event);
      let flag = true;
      this.$refs.videoPlayer.$el.querySelector(
        "button.vjs-playing"
      ).onclick = () => {
        flag = !flag;
        if (flag) {
          this.$emit("play");
        } else {
          this.playerBigBtn.style.display = "block";
          // this.$emit('stop');
        }
      };
    },
    playerStateChanged(event) {
      console.log("playerStateChanged");
      this.$emit("statechanged", event);
    },
    playerReadied() {
      console.log("playerReadied");
      this.$emit("ready");
    },
    // settingChange(e) {
    //   this.$emit("settingChange");
    // },
    async recordVideo(event) {
      this.recordVideoVisible = true;
      let { data } = await recordVideo({
        live_uuid: this.data.uu_id,
        rtmp: this.source.src,
        time: 10, //单位秒
        // "project_id": this.data.project_id
      });
      this.recordVideoVisible = false;
      if (data.errno !== 0) {
        this.$message({
          type: "error",
          message: data.message,
        });
      }
    },
    async screenshot() {
      this.screenshotVisible = true;
      let { data } = await screenshot({
        live_uuid: this.data.uu_id,
        rtmp: this.source.src,
        num: 1,
        // "project_id": this.data.project_id
      });
      this.screenshotVisible = false;

      if (data.errno !== 0) {
        this.$message({
          type: "error",
          message: data.message,
        });
      }
      this.$emit("eventType", { type: "recordVideo", event });
    },
    playback(event) {
      this.playbackVisible = true;
      this.$emit("eventType", { type: "playback", event });
      // this.playerBigBtn.style.display = 'block';
      // this.$refs.videoPlayer.player.pause();//该方法为兼容直推摄像头 点击 playback无法停止播放
      // this.$emit('stop');
    },
    viewScreenshot(event) {
      this.viewScreenshotVisible = true;
      this.$emit("eventType", { type: "screenshot", event });
    },
    audio(event) {
      this.audioClicked = !this.audioClicked;
      this.$emit("eventType", { type: "audio", event });
    },
    recordAudio(event) {
      this.recordAudioVisible = !this.recordAudioVisible;
      this.$emit("eventType", { type: "recordAudio", event });
    },
    setting(event) {
      this.settingVisible = true;
      this.$emit("eventType", { type: "setting", event });
    },
    alarm(event) {
      this.$emit("alarm");
      this.$emit("eventType", { type: "alarm", event });
    },
    closeDetails(event) {
      this.$emit("eventType", { type: "closeDetails", event });
    },
    disposeVideo() {
      if (this.playerType == "flv") this.flvDisposeVideo();
      this.$refs.videoPlayer.dispose();
    },
  },
  deactivated() {
    // this.disposeVideo();
  },
  beforeDestroy() {
    this.disposeVideo();
  },
};
</script>
<style lang="scss" scoped>
section {
  width: 100%;
  height: 100%;
  background: gray;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  > .title {
    height: 30px;
    color: #ffffff;
    padding-left: 8px;
    overflow: hidden;
  }
  .title-left > span {
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
    white-space: nowrap;
    display: inline-block;
  }
  .title-right > .button-group {
    height: 30px;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    overflow-y: auto;
    .el-button {
      margin: 0;
      border: none;
      color: #29e449;
    }
    .el-button--primary.is-plain {
      background: gray;
      // color: #29e449;
    }

    .el-button--primary.is-plain:hover {
      color: #fff;
    }
  }
  .disabled-color {
    color: #c0bcbc;
  }

  .enabled-color {
    color: #29e449;
  }

  .video-player ::v-deep .video-js .vjs-big-play-button {
    top: calc(50% - 0.9rem);
    left: calc(50% - 3rem);
  }
  //  .video-player ::v-deep  .vjs-progress-holder .vjs-slider{
  //    display: none;
  //  }

  .video-player ::v-deep .vjs-operation {
    width: 100px;
    height: 100px;
    background: rgba(255, 255, 255, 0.6);
    position: absolute;
    right: 0;
    bottom: 30px;
    border-radius: 50%;
  }
  .video-player ::v-deep .vjs-operation .vjs-operation-btn {
    width: 30px;
    height: 30px;
    background: rgba(0, 0, 0, 0.3);
    position: absolute;
    border-radius: 50%;
    font-size: 20px;
    line-height: 30px;
    text-align: center;
    color: #fff;
    overflow: hidden;
  }
  .video-player ::v-deep .vjs-operation .vjs-operation-btn:after {
    content: "";
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
    border-radius: 50%;
    background-image: radial-gradient(
      circle,
      rgb(238, 238, 238) 10%,
      transparent 10.01%
    );
    background-repeat: no-repeat;
    background-position: 50%;
    transform: scale(10, 10);
    opacity: 0;
    transition: transform 0.3s, opacity 0.5s;
  }
  .video-player ::v-deep .vjs-operation .vjs-operation-btn:active:after {
    transform: scale(0, 0);
    opacity: 0.3;
    transition: 0s;
  }
  .circle {
    display: inline-block;
    vertical-align: middle;
    width: 14px;
    height: 14px;
    margin-right: 4px;
    border-radius: 50%;
  }
  .circle-online {
    background: #7cfe39;
    box-shadow: 0px 0px 10px #fff;
  }
  .circle-offline {
    background: #fd5e5e;
    box-shadow: 0px 0px 10px #ddd;
  }
  .circle-undefind {
    background: #d0cccc;
    box-shadow: 0px 0px 10px #ddd;
  }
  .alarm-actived {
    animation: alarm-actived 1.5s infinite;
    -webkit-animation: alarm-actived 1.5s infinite;
    text-shadow: 0px 0px 4px #73f508;
  }
  @keyframes alarm-actived {
    0% {
      color: #ee3d3d;
    }
    50% {
      color: #ff0606;
      transform: scale(1.1);
    }
    100% {
      color: #ee3d3d;
    }
  }
  .alarm-unactived {
    color: #29e449;
  }
  .video-container {
    background: #000;
    flex: auto;
  }
}
</style>